package data.platfrom.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;

import data.framework.utils.ServletUtils;
import data.platfrom.Constants;
import data.platfrom.service.LoginServiceImpl;

@Controller
public class LoginController {
	@Autowired
	public LoginServiceImpl loginServiceImpl;

	@RequestMapping(value = "/index.do")
	public String index(HttpServletRequest request, ModelMap model) {
		// loginServiceImpl.memberLoginQuery();
		// return new ModelAndView("/main");
		Cookie cookie = WebUtils.getCookie(request, Constants.COOKIE_KEY);
		if (cookie != null) {
			String cookieValueStr = cookie.getValue();
			String[] cookieValues = StringUtils.split(cookieValueStr,
					Constants.COOKIE_SPLIT);
			if (cookieValues != null && cookieValues.length > 0) {
				if (cookieValues[0] != null) {
					model.put("account", cookieValues[0]);
					model.put("rememberAccount", "on");
				}
				if (cookieValues.length > 1 && cookieValues[1] != null) {
					model.put("password", cookieValues[0]);
					model.put("rememberPassword", "on");
				}
			}
		}

		return "/login";
	}

	@RequestMapping(value = "/login.do")
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> params = ServletUtils.getParametersStartingWith(
				request, "");
		String account = (String) params.get("account");
		String password = (String) params.get("password");
		String rememberAccount = (String) params.get("rememberAccount");
		String rememberPassword = (String) params.get("rememberPassword");
		if ("on".equals(rememberAccount)) {
			Cookie cookie;
			if ("on".equals(rememberPassword)) {
				cookie = new Cookie(Constants.COOKIE_KEY, account
						+ Constants.COOKIE_SPLIT + password);
			} else {
				cookie = new Cookie(Constants.COOKIE_KEY, account);
			}
			cookie.setMaxAge(1209600);// 两个星期
			response.addCookie(cookie);
		}

		response.getWriter().print("ok");
		response.getWriter().close();
		// loginServiceImpl.memberLoginQuery();
	}

	@RequestMapping(value = "/main.do")
	public String main() {
		return "main";
	}
}
